/**
 * Created by zhourh on 2018/6/15.
 *
 * 给定一个整数数组  nums，求出数组从索引 i 到 j  (i ≤ j) 范围内元素的总和，包含 i,  j 两点
 *
 *
 * 你可以假设数组不可变。
 会多次调用 sumRange 方法。

 动态规划
 */
public class RangeSumQueryImmutable {


    public static void main(String[] args) {
        int[] nums = new int[]{-2, 0, 3, -5, 2, -1};
        RangeSumQueryImmutable rangeSumQueryImmutable = new RangeSumQueryImmutable(nums);
        System.out.println(rangeSumQueryImmutable.sumRange(0,2));
        System.out.println(rangeSumQueryImmutable.sumRange(2,5));
        System.out.println(rangeSumQueryImmutable.sumRange(0,5));

    }

    private int[] nums;
    private int[] sums;

    public RangeSumQueryImmutable(int[] nums) {
        this.nums = nums;
        if (nums != null && nums.length > 0) {
            sums = new int[nums.length];
            sums[0] = nums[0];
            for (int i = 1; i < sums.length; i++) {
                sums[i] = nums[i] + sums[i - 1];
            }
        }

    }

    public int sumRange(int i, int j) {
        if (sums == null) {
            return 0;
        }
        if (i < 0 || j > nums.length || i > j) {
            return 0;
        }

        if (i == 0) {
            return sums[j];
        } else {
            return sums[j] - sums[i-1];
        }

    }
}
